<template>
    <section>
        <div  v-loading="saveLoading" style="display:table;width:100%;">
            <el-col align="right">
                <div class="section">
                    <div class="head-left">
                        <span class="school">{{reportData.check_unit}}报告</span>
                            <el-button type=text @click="toggleLeft">
                                <span v-if="leftClose===0">收起资料区</span>
                                <span v-else>展开资料区</span>
                            </el-button>
                    </div>
                    <el-button type="primary" @click="preview">预览</el-button>
                    <el-button
                            type="primary"
                            plain
                            :disabled="saveLoading"
                            @click="save">保存</el-button>
                    <el-button type="primary" plain @click="cancel">返回</el-button>
                </div>
            </el-col>
            <el-col>
                <div class="records-body">
                    <div   :class="[{'dispnone':leftClose===1},'inspect-items']">
                        <div class="body-item">
                            <div class="body-title body-top-title">资料区</div>
                            <div class="inspect-comment">
                                <div class="val-title">综合意见</div>
                                <div class="val-val">
                                    <div v-for="(item, index) in reportData.check_work_list.check_work"
                                         v-if="item.suggestion && item.suggestion.length > 0"
                                         class="suggestion-item">
                                        <div class="suggestion-title"><img src="/assets/images/icon_zhuanjia.png" class="icon-zhuanjia"/> {{item.check_user_name}} </div>
                                        <div class="suggestion-content">
                                            <el-input
                                                    :autosize="true"
                                                    type="textarea"
                                                    resize="none"
                                                    class="showTextConter"
                                                    v-model="item.suggestion"
                                                    readonly>
                                            </el-input>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="body-item">
                            <div class="body-title">检查项</div>
                            <div v-for="(item, index) in inspect_list" class="inspect-item">
                                <div class="inspect-head">
                                    <div class="head-title">
                                        <div class="record-title  m-left-20">
                                            <!--<span class="star">{{formatStar(item.star_level)}}</span>-->
                                            <span>{{item.check_item_three_order_number + '.&nbsp;' + item.check_item_three }}</span>
                                        </div>
                                        <div class="record-action"
                                             style="text-align: right"
                                        >
                                            <a href="javascript:"
                                               style="display:inline-block;"
                                               @click="toggleCollapseLeft(item.check_item_three_id, index)">{{formatToggle(item.display)}}</a>
                                            <a href="javascript:"
                                               style="display:inline-block;margin-left:30px;"
                                               @click="addThisInspectItem(item)">导入</a>
                                        </div>
                                    </div>
                                </div>

                                <div class="inspect-body" :class="item.display">
                                    <div v-for="(check_item, index) in item.check_items" class="record-item">
                                        <div v-if="index > 0" class="line"/>
                                        <span class="info-content" style="display: block;  padding:20px 0 10px; color:#333;"><img src="/assets/images/icon_zhuanjia.png" class="icon-zhuanjia"/> {{check_item.create_user_name}}</span>
                                        <div  v-if="check_item.desc" class="record-info" style="margin-top:0;">
                                            <div class="info-title">描述信息</div>
                                            <!--<span :class="'cyc cyc-' + formatCyc(check_item.check_content_status)"
                                                  style="float:right; margin:16px 15px 0 0;">&nbsp;</span>-->
                                            <div class="info-content info-check-item-desc" v-if="check_item.desc">

                                                <el-input
                                                        :autosize="true"
                                                        type="textarea"
                                                        resize="none"
                                                        class="showTextConter"
                                                        v-model="check_item.desc"
                                                        style="color:#333"
                                                        readonly>

                                                </el-input>
                                            </div>
                                        </div>
                                        <div class="record-info" v-if="check_item.image_list.length > 0">
                                            <div class="info-title">图片</div>
                                            <div class="info-img">
                                                <img v-for="img in check_item.image_list" @click="showImg(img.path)" :src="fixUrl(img.path)"/>
                                            </div>
                                        </div>
                                        <div class="record-info" v-if="check_item.building_room.length > 0">
                                            <div class="info-title">楼宇 - 房间号</div>
                                            <div class="info-lab">
                                                <div>
                                                    <el-tag  v-for="(lab, index) in check_item.building_room" :key="index" class="info-item" type="success" style="margin-right:15px;">{{lab.building}}</el-tag>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>


                <div :class="[{'full':leftClose===1},'report-items']">
                    <div class="body-item">
                        <div class="body-title body-top-title">编辑区</div>
                    </div>
                    <div class="body-item">
                        <div class="report-comment">
                            <div class="val-title"><span style="color:#f00"> * </span>综合意见</div>
                            <div class="val-val">
                                <el-form :model="reportData" ref="reportData" :rules="reportDataRules" style="margin-top:-15px;">
                                    <el-form-item prop="suggestion">
                                        <el-input
                                                class="border-none"
                                                type="textarea"
                                                maxlength="1000"
                                                resize="none"
                                                :autosize="true"
                                                placeholder="请输入您的检查综合意见"
                                                v-model="reportData.suggestion">
                                        </el-input>
                                        <span style="float:right; line-height:14px; color:#999;">{{ reportData.suggestion ? reportData.suggestion.length :  0 }} / 1000</span>
                                    </el-form-item>
                                </el-form>
                            </div>
                        </div>
                    </div>
                    <div class="body-item">
                        <a href="javascript:" class="inspect-add" @click="addInspectItem">+ 检查项</a>
                    </div>
                    <div v-for="(item ,index) in reportData.check_item_desc" class="body-item">
                        <div class="report-item">

                            <div class="record-head">
                                <div class="record-title">
                                    <!--<span class="star">{{formatStar(item.star_level)}}</span>-->
                                    <span>{{item.check_item_three_order_number + '.&nbsp;' + item.check_item_three }}</span>
                                </div>
                                <div class="record-action">
                                    <a href="javascript:"
                                       style="display: inline-block"
                                       @click="toggleCollapseRight(item.check_item_three_id)">{{formatToggle(item.display)}}</a>
                                    <a href="javascript:"
                                       @click="remove(item.check_item_three_id)"
                                       style="display:inline-block;margin-left:30px;color:red;">删除</a>
                                </div>
                            </div>

                            <div  :class="{ [item.display]: pageInit }"  :style="{'opacity:0':!pageInit}">
                                <div class="record-info">
                                    <div class="info-title">
                                        <span>图片<span style="font-size: 14px; color:#999;"> (最多可上传十张图片)</span></span>&nbsp;&nbsp;&nbsp;&nbsp;
                                        <a class="btn-small" href="javascript:" v-if="item.image_list.length < 10"
                                           @click="addImgFromAsset(item.check_item_three_id, item.image_list.length)">从资料区导入</a>
                                    </div>
                                    <div class="info-img">
                                        <el-upload
                                                class="avatar-uploader"
                                                action=""
                                                multiple
                                                :data={index:index}
                                                :class="item.image_list.length >= 10 ? 'uplaod-img-but-hid': ''"
                                                list-type="picture-card"
                                                :http-request="httpRequest"
                                                :file-list="item.image_list"
                                                :on-success="handleAvatarSuccess"
                                                :on-error="handleAvatarError"
                                                :before-remove="(file, imgList) => handleBeforeRemove(file, imgList, index)"
                                                :on-remove="handleRemove"
                                                :on-preview="(file) => showImg(file.path)"
                                                :limit="10"
                                                :on-exceed="handleExceed"
                                                :before-upload="beforeAvatarUpload">
                                            <i class="el-icon-plus avatar-uploader-icon"
                                               style="height: 75px; width:75px"></i>
                                        </el-upload>
                                    </div>
                                </div>


                                <div class="record-info">
                                    <div class="info-title">
                                        <span>楼宇 - 房间号</span>
                                        <i class="el-icon-circle-plus"
                                           style="color: #20a0ff; cursor: pointer;font-size: 20px; vertical-align: middle"
                                           @click="openRoomDialog(item.check_item_three_id)">
                                        </i>
                                    </div>
                                    <!--<div v-for="(lab, index) in item.building_room" class="info-lab">
                                        <span>{{lab.building}}</span>
                                        <i class="el-icon-circle-close-outline"
                                           style="color: #20a0ff; cursor: pointer;font-size: 16px; vertical-align: middle"
                                          >
                                        </i>
                                    </div> -->
                                    <div class="info-lab">
                                        <el-tag
                                                v-for="(lab, index) in item.building_room"
                                                :key="index"
                                                @close="removeRoom(item.check_item_three_id, index)"
                                                closable
                                                style="margin-right:15px;"
                                                type="success">
                                            {{lab.building}}
                                        </el-tag>
                                    </div>
                                    <div class="info-content">
                                        <span style="color: #000;font-weight: bolder; display: inline-block">
                                            <span style="color:#f00"> * </span>描述信息
                                        </span>
                                        <el-input
                                                class="border-none textarea-bg"
                                                type="textarea"
                                                :autosize="true"
                                                resize="none"
                                                placeholder="请输入您的描述信息"
                                                v-model="item.desc">
                                        </el-input>
                                    </div>
                                </div>

                                <!--   <div class="record-level">
                                       <span v-if="item.check_content_status == '2'"
                                             class="cyc cyc-margin cyc-green">&nbsp;</span>
                                       <span v-if="item.check_content_status != '2'"
                                             @click="setStatus(item.check_item_three_id, '2')"
                                             class="cyc cyc-margin">&nbsp;</span>
                                       <span>有亮点</span>
                                       <span v-if="item.check_content_status == '1'"
                                             class="cyc cyc-margin cyc-orange">&nbsp;</span>
                                       <span v-if="item.check_content_status != '1'"
                                             @click="setStatus(item.check_item_three_id, '1')"
                                             class="cyc cyc-margin">&nbsp;</span>
                                       <span>待改进</span>
                                       <span v-if="item.check_content_status == '0'"
                                             class="cyc cyc-margin cyc-red">&nbsp;</span>
                                       <span v-if="item.check_content_status != '0'"
                                             @click="setStatus(item.check_item_three_id, '0')"
                                             class="cyc cyc-margin">&nbsp;</span>
                                       <span>不合格</span>
                                   </div>-->
                            </div>
                        </div>
                    </div>
                </div>
            </el-col>
        </div>

        <!--对话框-显示大图-->
        <el-dialog title="显示大图" :visible.sync="big_img_dialog.show">
            <img class="big-img" :src="big_img_dialog.path">
        </el-dialog>
        <!--对话框-添加检查项-->
        <el-dialog title="添加检查项" fullscreen :visible.sync="inspectDialogVisible" @open="inspectDialogOpen">
            <addInspectItemDialog v-on:closeDialog="inspectDialogClose"></addInspectItemDialog>
        </el-dialog>
        <!--对话框-添加图片-->
        <el-dialog title="从资料区选择图片" :visible.sync="add_img_dialog.show" @open="imgDialogOpen">
            <div class="add-img">
                <div v-if="source_img_list.length > 0">
                    <div v-for="(inspect, i) in source_img_list" class="add-img-room">
                        <div class="add-img-room-name">
                            {{inspect.check_item_three_order_number}} {{inspect.name}}
                        </div>
                        <div class="add-img-list">
                            <img v-for="(img, j) in inspect.img_list" :src="fixUrl(img.path)"
                                 @click="toggleSelectImg(i, j)"
                                 :class="{selected: (isSelected(i, j))}"/>
                        </div>
                    </div>
                </div>
                <div v-else>
                    <span style="display:block; text-align:center;line-height:90px; color:#999;">暂无资料图片</span>
                </div>
            </div>
            <div class="add-img-btn">
                <el-button type="primary" plain @click="cancelAddImg">取消</el-button>
                <el-button type="primary" @click="addImg">导入</el-button>
            </div>
        </el-dialog>
        <!--对话框-预览-->
        <el-dialog title="报告预览" fullscreen :visible.sync="preview_dialog.show" @close="reload" @open="previewDialogOpen" custom-class="bgColor">
            <el-card class="box-card" style="max-width:1000px; padding:20px 50px; margin:30px auto;">
                <previewDialog :receiverCount="preview_dialog.count"
                               :id="id"
                               :resource_url="resource_url"
                               :tempData="preview_dialog.temp_data"
                               v-on:closeDialog="previewDialogClose">
                </previewDialog>
            </el-card>
        </el-dialog>
        <!-- 楼宇及房间号 -->
        <el-dialog :title="dialog.title" :visible.sync="dialog.dialogFormVisible" :before-close="resetDialogData" width="30%">

            <el-form :model="dialog" ref="dialog" :rules="dialog_rules" :label-width="dialog.formLabelWidth" style="margin-top:50px;">

                <el-form-item label="楼宇及房间号:" prop="building">
                    <el-input placeholder="请输入楼宇及房间号" type="text" v-model="dialog.building"></el-input>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer" style="padding:0;">
                <el-button type="primary" @click="addRoom">添加</el-button>
            </div>
        </el-dialog>

    </section>
</template>

<script>
    import * as api from '../../api/report_api'
    import dict from '../../common/js/dict';
    import addInspectItemDialog from '../records/add';
    import previewDialog from './preview';
    import {update_img, getResourceUrl} from '../../api/common';
    import lrz from "lrz"

    export default {
        inject: ['reload'],
        data() {
            return {
                pageInit:false,
                 leftClose:0,
                id: '',
                inspectDialogVisible: false,
                loading: false,
                dialog: {
                    key: '',
                    formLabelWidth: '120px',
                    title: '添加楼宇及房间号',
                    dialogFormVisible: false,
                    building: '',
                    room: ''
                },
                dialog_rules: {
                    building: [
                        {required: true, message: '请输入楼宇及房间号', trigger: 'blur'}
                    ]
                },
                add_img_dialog: {
                    show: false,
                    imglength: 0,
                    id: ''
                },
                big_img_dialog: {
                    show: false,
                    path: ''
                },
                preview_dialog: {
                    temp_data: {},
                    show: false,
                    count: 0
                },
                deleted_desc_id: [],
                source_desc_id: [],
                resource_url: '',
                inspect_list: [],
                source_img_list: [],
                source_img_all: [],
                selected_img_list: [],
                remove_img_lock: false,
                saveLoading: true,
                reportDataRules: {
                    suggestion: [
                        { min: 0, max: 1000, message: '综合意见最多输入1000字', trigger: 'change'}
                    ],
                },
                //表格数据
                reportData: {
                    check_unit: '',
                    check_work_list: {
                        check_work: [],
                    }
                }
            }
        },
        components: {
            addInspectItemDialog,
            previewDialog
        },
        methods: {
              toggleLeft(){
                this.leftClose=this.leftClose===0?1:0
            },
            showImg(path) {
                this.big_img_dialog.path = this.fixUrl(path);
                this.big_img_dialog.show = true;
            },

            addThisInspectItem(item) {
                this.checkAndAddInspectItem(item);
            },
            addInspectItem() {
                this.inspectDialogVisible = true;
            },
            inspectDialogOpen() {
            },

            checkAndAddInspectItem(val) {
                if (val && val.check_item_three_id) {
                    this.reportData.check_item_desc = this.reportData.check_item_desc || [];

                    let item = this.reportData.check_item_desc.find((value, index, arr) => {
                        return value.check_item_three_id == val.check_item_three_id;
                    });

                    if (item && item.check_item_three_id) {
                        this.$message({
                            type: 'info',
                            message: '检查项已存在'
                        });
                    }
                    else {
                        item = {
                            display: 'show',
                            star_level: val.star_level,
                            check_item_three_order_number: val.check_item_three_order_number,
                            check_item_three_item_order: val.check_item_three_item_order,
                            check_item_one_id: val.check_item_one_id,
                            check_item_one: val.check_item_one,
                            check_item_two_id: val.check_item_two_id,
                            check_item_two: val.check_item_two,
                            check_item_three_id: val.check_item_three_id,
                            check_item_three: val.check_item_three,
                            building_room: [],
                            image_list: [],
                            check_content_status: '0',
                            desc: ''
                        };
                        if(val.check_items && val.check_items.length > 0){
                            val.check_items.map(subItem => {
                                if(subItem.building_room && subItem.building_room.length > 0) item.building_room = item.building_room.concat(subItem.building_room);
                                if(subItem.desc && subItem.desc != '') item.desc = item.desc + subItem.desc + '\n';
                                if(subItem.image_list && subItem.image_list.length > 0) {
                                    subItem.image_list.map(imgItem => {
                                        let tempImageItem = imgItem;
                                            tempImageItem.name = imgItem.origin_name;
                                            tempImageItem.url = imgItem.path;
                                            item.image_list.push(tempImageItem)
                                    })
                                }
                            })
                        }
                        this.reportData.check_item_desc.unshift(item);
                        this.$message({
                            type: 'success',
                            message: '检查项导入成功'
                        });
                        if(item.image_list.length > 10) {
                            this.timer = setTimeout(() => {
                                this.$notify({
                                    title: '提示',
                                    message: '当前导入检查项图片数量超出十张，请调整',
                                    type: 'warning'
                                });
                                clearTimeout(this.timer)
                            }, 800)
                        }
                    }
                }
            },
            inspectDialogClose(val) {
                this.inspectDialogVisible = false;
                this.checkAndAddInspectItem(val);
            },

            remove(id) {

                this.$confirm('确认删除此检查项？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    closeOnClickModal: false,   //不通过点击遮罩关闭弹框
                    type: 'info'
                }).then(() => {

                    if (this.reportData.check_item_desc && this.reportData.check_item_desc.length > 0) {
                        let index = this.reportData.check_item_desc.findIndex((value, index, arr) => {
                            return value.check_item_three_id == id;
                        });
                        if (index > -1) {
                            let item_id = this.reportData.check_item_desc[index].id;
                            if (item_id && item_id.length > 0) {
                                this.deleted_desc_id.push(item_id);
                            }
                            this.reportData.check_item_desc.splice(index, 1);
                        }
                    }


                }).catch((e) => {
                    /*this.$message({
                        type: 'info',
                        message: e.message
                    });*/
                });
            },
            addImgFromPC(id) {
            },
            handleAvatarSuccess(res, file, list) {
            },
            handleAvatarError(err, file, list) {

            },
            handleExceed(files, fileList) {

                this.$message.warning(`最多可上传十张图片`);
            },
            beforeAvatarUpload(file) {
                const splitLength = file.name.toLowerCase().split('.').length;
                const extension = file.name.toLowerCase().split('.')[splitLength - 1];
                const extension_array = ['jpg', 'png', 'jpeg'];

                const isJPG = (extension_array.indexOf(extension) > -1);
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('上传图片只能是 JPG 或 PNG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },
            handleBeforeRemove(file, imgList, itemImageIndex) {
                this.reportData.check_item_desc[itemImageIndex].image_list = imgList;
               /* if (this.remove_img_lock) {
                    return false;
                }
                for (let i = 0; i < this.reportData.check_item_desc.length; i++) {
                    if (this.reportData.check_item_desc[i].check_item_three_id == file.parent) {
                        let img_list = this.reportData.check_item_desc[i].image_list;
                        let index = img_list.findIndex(function (value, index, arr) {
                            return value.id == file.id;
                        });


                        if (index > -1) {
                            img_list.splice(index, 1);

                        }
                        else {
                            this.remove_img_lock = false;
                            return false;
                        }

                        this.remove_img_lock = false;
                        return true;
                        this.reportData.check_item_desc[i].image_list = imgList
                    }
                }*/

            },
            handleRemove(file, imgList) {

            },
            httpRequest(item) {
                let image_list = this.reportData.check_item_desc[item.data.index].image_list;
                let formData = new FormData();
                lrz(item.file, {
                    width: 1280 //设置压缩参数
                }).then((rst) => {
                    this.importLoading = true;
                    formData = rst.formData;
                    update_img(formData).then((res) => {
                        let result = JSON.parse(res.data.datas);
                        this.importLoading = false;
                        if (res.data.status == 200) {
                            image_list.push({
                                id: result.id,
                                url: result.url,
                                parent: this.reportData.check_item_desc[item.data.index].check_item_three_id
                            });
                        } else {
                            if (res.data.status === 401) {
                                this.$router.push('/login');
                            }
                            this.$message.error(res.data.msg);
                        }
                    });

                }).catch(function (err) {
                    this.$message.error('压缩失败');
                }).always(function () {
                    // 清空文件上传控件的值
                    e.target.value = null
                })


            },

            addImgFromAsset(id, selectImageLength) {

                // 所有资源图片
                if (this.source_img_all.length == 0) {
                    if (this.inspect_list && this.inspect_list.length > 0) {
                        for (let i = 0; i < this.inspect_list.length; i++) {
                            let item = this.inspect_list[i];

                            if (item && item.check_items && item.check_items.length > 0) {
                                for (let j = 0; j < item.check_items.length; j++) {
                                    let check_item = item.check_items[j];


                                    let inspect = {
                                        name: item.check_item_three,
                                        check_item_three_order_number: item.check_item_three_order_number,
                                        rooms: check_item.building_room || [],
                                        img_list: []
                                    };
                                    if (check_item && check_item.image_list && check_item.image_list.length > 0) {
                                        for (let k = 0; k < check_item.image_list.length; k++) {
                                            let img_item = check_item.image_list[k];
                                            img_item.url = this.fixUrl(img_item.path);
                                            img_item.class = "";
                                            inspect.img_list.push(img_item);
                                        }
                                    }
                                    this.source_img_all.push(inspect);

                                }
                            }

                        }
                    }
                }

                // 计算已有的图片
                let exclude_img_list = [];
                let item = this.reportData.check_item_desc.find(function (val, idx, arr) {
                    return val.check_item_three_id == id;
                });

                if (item && item.image_list && item.image_list.length > 0) {
                    for (let i = 0; i < item.image_list.length; i++) {
                        exclude_img_list.push(item.image_list[i].id);
                    }
                }

                // 排除已有的图片
                this.source_img_list = [];
                if (this.source_img_all.length > 0) {
                    for (let i = 0; i < this.source_img_all.length; i++) {

                        let item = this.source_img_all[i];
                        if (item && item.img_list.length > 0) {

                            let inspect = {
                                name: item.name,
                                rooms: item.rooms,
                                check_item_three_order_number:item.check_item_three_order_number,
                                img_list: []
                            };

                            for (let j = 0; j < item.img_list.length; j++) {
                                let img = item.img_list[j];
                                inspect.img_list.push(img);
                                // if (exclude_img_list.indexOf(img.id) < 0) {
                                //     inspect.img_list.push(img);
                                // }
                            }

                            if (inspect.img_list.length > 0) {
                                this.source_img_list.push(inspect);
                            }
                        }
                    }
                }
                this.add_img_dialog.id = id;
                this.add_img_dialog.imglength = selectImageLength;
                this.add_img_dialog.show = true;
            },

            isSelected(inspect_index, img_index) {

                let i = this.selected_img_list.findIndex(function (val, idx, arr) {
                    return (val[0] == inspect_index && val[1] == img_index);
                });

                return (i > -1);
            },
            toggleSelectImg(inspect_index, img_index) {

                let index = [inspect_index, img_index];
                let i = this.selected_img_list.findIndex(function (val, idx, arr) {
                    return (val[0] == index[0] && val[1] == index[1]);
                });
                if (i > -1) {
                    this.selected_img_list.splice(i, 1);
                } else {
                    if((this.selected_img_list.length + this.add_img_dialog.imglength) > 9 ) return this.$message.warning(`每条检查项最多可上传十张图片`);
                    this.selected_img_list.push(index);
                }
            },
            addImg() {

                if (this.selected_img_list.length > 0) {

                    this.selected_img_list = this.selected_img_list.sort(function (a, b) {
                        return b[0] - a[0];
                    });
                    let id = this.add_img_dialog.id;
                    let item = this.reportData.check_item_desc.find(function (val, idx, arr) {
                        return val.check_item_three_id == id;
                    });

                    item.image_list = item.image_list || [];

                    if (item.image_list.length > 10 ||this.selected_img_list.length + item.image_list.length > 10 ) {
                        this.$message.warning(`最多可上传十张图片`);
                        return false
                    }
                    item.building_room = item.building_room || [];

                    for (let i = this.selected_img_list.length - 1; i >= 0; i--) {
                        let index = this.selected_img_list[i];


                        let inspect = this.source_img_list[index[0]];


                        let img = Object.assign({}, inspect.img_list[index[1]]);

                        img.parent = id;

                        item.image_list.push(img);

                        this.selected_img_list.splice(i, 1);

                        if (inspect.rooms.length > 0) {

                            for (let j = 0; j < inspect.rooms.length; j++) {
                                let room = inspect.rooms[j];

                                if(room.building && room.building.length > 0){

                                    let building_index = item.building_room.findIndex(function (val, idx, arr) {
                                        return val.building == room.building;
                                    });
                                    if (building_index < 0) {
                                        item.building_room.push({
                                            building: room.building
                                        });
                                    }
                                }
                            }
                        }


                    }

                }
                this.add_img_dialog.show = false;
                this.add_img_dialog.imglength = 0;
            },
            cancelAddImg() {
                this.selected_img_list = [];
                this.add_img_dialog.show = false;
            },
            imgDialogOpen() {

            },

            imgDialogClose() {
                this.inspectDialogVisible = false;
            },
            previewDialogOpen() {
            },

            previewDialogClose() {
                this.preview_dialog.show = false;
                this.reload();
            },
            toggleCollapseRight(id) {

                if (this.reportData.check_item_desc && this.reportData.check_item_desc.length > 0) {
                    let item = this.reportData.check_item_desc.find((value, index, arr) => {
                        return value.check_item_three_id == id;
                    });

                    if (item) {
                        let cls = item.display || 'show';
                        item.display = (cls == 'show' ? 'hide' : 'show');

                    }
                }
            },
            toggleCollapseLeft(id, index) {
                this.$forceUpdate();
                let item = this.inspect_list[index];
                item.display = (item.display && item.display == 'show') ? 'hide' : 'show';


            },
            openRoomDialog(id) {
                this.dialog.key = id;
                this.dialog.dialogFormVisible = true;
            },
            addRoom() {
                this.$refs['dialog'].validate((valid) => {
                    if (valid) {
                        let item = this.reportData.check_item_desc.find((value, index, arr) => {
                            return value.check_item_three_id == this.dialog.key;
                        });

                        if (item) {
                            item.building_room = item.building_room || [];
                            item.building_room.push({
                                building: this.dialog.building
                            });
                        }
                        this.resetDialogData();
                    }
                });
            },
            resetDialogData() {
                this.dialog.building = '';
                this.dialog.room = '';
                this.dialog.dialogFormVisible = false;
            },
            removeRoom(id, index) {
                if (this.reportData.check_item_desc && this.reportData.check_item_desc.length > 0) {
                    let item = this.reportData.check_item_desc.find((value, index, arr) => {
                        return value.check_item_three_id == id;
                    });

                    if (item && item.building_room && item.building_room.length > 0) {
                        item.building_room.splice(index, 1);
                    }
                }
            },
            setStatus(id, status) {
                if (this.reportData.check_item_desc && this.reportData.check_item_desc.length > 0) {
                    for (let i = 0; i < this.reportData.check_item_desc.length; i++) {
                        if (this.reportData.check_item_desc[i].check_item_three_id == id) {
                            this.reportData.check_item_desc[i].check_content_status = status;
                            break;
                        }
                    }
                }
            },
            formatCyc(status) {

                switch (status.toString()) {
                    case '0':
                        return 'red';
                    case '2':
                        return 'green';
                    case '1':
                    default:
                        return 'orange';
                }
            },
            formatStar(cnt) {
                switch (cnt) {
                    case '1':
                        return '★';
                    case '2':
                        return '★★';
                    case '3':
                        return '★★★';
                    case '0':
                    default:
                        return '';
                }
            },
            formatToggle(txt) {
                if (txt && txt == 'hide') {
                    return '展开';
                }
                return '收起';
            },
            openPreviewDialog() {
                this.preview_dialog.count++;

                let star_0 = 0;
                let star_1 = 0;
                let star_2 = 0;
                let star_3 = 0;

                let check_item_very_count = 0;
                let check_item_con_count = 0;
                let check_item_uncount = 0;
                let item_list = this.reportData.check_item_desc || [];
                if (item_list.length > 0) {
                    for (let i = 0; i < item_list.length; i++) {
                        let item = item_list[i];
                        if (item.check_content_status == '0') {
                            check_item_uncount++;
                            switch (item.star_level) {
                                case '0':
                                    star_0++;
                                    break;
                                case '1':
                                    star_1++;
                                    break;
                                case '2':
                                    star_2++;
                                    break;
                                case '3':
                                    star_3++;
                                    break;
                                default:
                                    break;
                            }
                        } else if (item.check_content_status == '1') {
                            check_item_con_count++
                        } else if (item.check_content_status == '2') {
                            check_item_very_count++;
                        }
                    }
                }
                let total = star_3 + star_2 + star_1 + star_0;
                let params = {
                    threecount: star_3,
                    twocount: star_2,
                    onecount: star_1,
                    totalcount: total
                }

                let tempData = {
                    id: this.$route.params.id,
                    check_item_very_count: check_item_very_count,
                    check_item_con_count: check_item_con_count,
                    check_item_uncount: check_item_uncount,
                    group_user_name: this.reportData.group_user_name,
                    check_unit: this.reportData.check_unit,
                    check_user: this.reportData.check_user,
                    suggestion: this.reportData.suggestion,
                    check_item_desc: item_list,
                    deleted_desc_id: this.getCurrentDeletedDescIdArray()
                };
                api.reportResult(params).then((res) => {
                    if (res.data.status == 200) {
                        let result = JSON.parse(res.data.datas);
                        tempData.check_result_preview = parseInt(result.check_result);

                        this.preview_dialog.temp_data = tempData;
                        this.preview_dialog.show = true;

                    } else {
                        if (res.data.status == 401) {
                            this.$router.push('/login');
                        }
                        this.$message.error(res.data.msg);
                    }
                });

            },
            preview() {
                this.$refs['reportData'].validate((valid) => {
                    if (valid) {
                        this.saveAndExecute(this.openPreviewDialog);
                    }
                });
            },
            fixUrl(url) {
                if (url && url.length > 0 && url.toLowerCase().indexOf("http:") != 0) {
                    return this.resource_url + url;
                }
                return url;
            },
            cancel() {
                this.$router.push('/report/records/' + this.$route.params.id);
            },
            save() {
                this.$refs['reportData'].validate((valid) => {
                    if (valid) {
                        this.saveLoading = true
                        this.saveAndExecute(this.initData); // 去掉保存reload
                        /*this.$confirm('确认保存报告？', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            closeOnClickModal: false,   //不通过点击遮罩关闭弹框
                            type: 'info'
                        }).then(() => {



                        }).catch((e) => {

                        });*/

                    }
                });
            },
            saveAndExecute(callback) {
                let params = {
                    id: this.$route.params.id,
                    suggestion: this.reportData.suggestion,
                    check_item_desc: this.reportData.check_item_desc || [],
                    deleted_desc_id: this.getCurrentDeletedDescIdArray()
                };
                let imageStatus = false
                params.check_item_desc.map((item, index) => {
                    if(item.image_list && item.image_list.length > 10) {
                        imageStatus = true
                        this.$message.warning(item.check_item_three_order_number + `检查项包含的图片数量多于十张，请调整`);
                    }
                })
                if(imageStatus){
                    this.saveLoading = false
                    return false
                }
                api.updateReport(params).then((res) => {
                    if (res.data.status == 200) {
                        this.$message({
                            type: 'success',
                            message: '保存成功'
                        });

                        if (callback) {
                            callback();
                        }

                    } else {
                        if (res.data.status == 401) {
                            this.$router.push('/login');
                        }
                        this.$message.error(res.data.status + " " + res.data.msg);
                        this.saveLoading = false
                    }
                }).catch(err => {
                    this.$message.error(err);
                    this.saveLoading = false
                });
            },
            getCurrentDescIdArray() {
                let array = [];
                if (this.reportData.check_item_desc && this.reportData.check_item_desc > 0) {

                    for (let i = 0; i < this.reportData.check_item_desc.length; i++) {
                        let id = this.reportData.check_item_desc[i].id;

                        if (id && id.length > 0) {
                            array.push(id);
                        }
                    }
                }
                return array;
            },
            getCurrentDeletedDescIdArray() {
                let array = [];
                if (this.deleted_desc_id.length > 0) {
                    let currentArray = this.getCurrentDescIdArray();
                    for (let i = 0; i < this.deleted_desc_id.length; i++) {
                        let id = this.deleted_desc_id[i];

                        if (currentArray.indexOf(id) < 0 && this.source_desc_id.indexOf(id) > -1) {
                            array.push(id);
                        }
                    }
                }
                return array;

            },
            getInspectItem(checkItem) {
                let id = checkItem.check_item_three_id;
                let inspect_item = this.inspect_list.find(function (value, index, arr) {
                    return value.check_item_three_id == id;
                });
                if (inspect_item) {
                    return inspect_item;
                }
                inspect_item = {
                    check_item_three_item_order: checkItem.check_item_three_item_order,
                    check_item_one_id: checkItem.check_item_one_id,
                    check_item_one: checkItem.check_item_one,
                    check_item_two_id: checkItem.check_item_two_id,
                    check_item_two: checkItem.check_item_two,
                    check_item_three_id: id,
                    check_item_three: checkItem.check_item_three,
                    star_level: checkItem.star_level,
                    check_item_three_order_number: checkItem.check_item_three_order_number,
                    check_items: []
                };
                this.inspect_list.push(inspect_item);
                return this.inspect_list[this.inspect_list.length - 1];
            },
            formatData(data) {
                if (data) {
                    this.inspect_list = [];
                    this.source_img_list = [];
                    this.source_img_all = [];
                    this.selected_img_list = [];
                    this.deleted_desc_id = [];
                    this.source_desc_id = [];
                    this.reportData.check_work_list = [];
                    if (data.check_work_list && data.check_work_list.check_item_desc && data.check_work_list.check_item_desc.length > 0) {
                        let check_list = data.check_work_list.check_item_desc;
                        for (let i = 0; i < check_list.length; i++) {
                            let check_item = check_list[i];
                            let inspect_item = this.getInspectItem(check_item);
                            inspect_item.display = 'hide';
                            inspect_item.check_items.push({
                                check_content_status: check_item.check_content_status,
                                image_list: check_item.image_list,
                                building_room: check_item.building_room,
                                check_type: check_item.check_type,
                                create_user_name: check_item.create_user_name,
                                desc: check_item.desc
                            });
                        }

                        this.inspect_list = this.inspect_list.sort(function (a, b) {
                            return a.check_item_three_item_order - b.check_item_three_item_order;
                        });
                        this.inspect_list[0].display = 'show';
                    }


                    if (data.check_item_desc && data.check_item_desc.length > 0) {

                        data.check_item_desc = data.check_item_desc.sort(function (a, b) {
                            return a.check_item_three_item_order - b.check_item_three_item_order;
                        });

                        for (let i = 0; i < data.check_item_desc.length; i++) {
                            let item = data.check_item_desc[i];
                            this.source_desc_id.push(item.id);
                            item.image_list = item.image_list || [];

                            if (item.image_list.length > 0) {
                                for (let j = 0; j < item.image_list.length; j++) {
                                    let sub_item = item.image_list[j];
                                    sub_item.parent = item.check_item_three_id;
                                    sub_item.url = this.fixUrl(sub_item.path || '');
                                }
                            }

                            item.display = 'hide';
                        }
                      //  data.check_item_desc[0].display = 'show'; //取消了默认展开
                    }

                }
                this.reportData = data;
                this.saveLoading = false
            },
            //初始化页面
            initData() {
                getResourceUrl().then((res) => {
                    if (res.data.status == 200) {
                        this.resource_url = res.data.datas;
                    } else {
                    }
                    let params = {
                        id: this.$route.params.id
                    };

                    api.getReportDetail(params).then((res) => {
                          setTimeout(()=>{
                                    this.pageInit = true
                            },100)
                        
                        if (res.data.status == 200) {
                            let data = JSON.parse(res.data.datas);
                            this.formatData(data);
                        } else {
                            if (res.data.status == 401) {
                                this.$router.push('/login');
                            }
                            this.$message.error(res.data.status + " " + res.data.msg);
                        }
                    });
                });
            }
        },
        mounted() {
            this.$nextTick(function () {
                this.id = this.$route.params.id;
                this.initData();
            })
        }
    }
</script>

<style scoped>
 
    .section {
        margin: 15px 0;
        border-bottom: solid 1px #ccc;
        padding: 15px 0 20px;
    }

    .head-left {
        padding-bottom: 15px;
        float: left;
    }

    .school {
        color: #000;
        font-size: 1.5em;
        font-weight: bold;
    }

    .head-right {
        margin-top: 15px;
        padding-bottom: 15px;
        float: right;
    }

    .cyc {
        border-radius: 5px;
        width: 10px;
        height: 10px;
        display: inline-block;
        display: -webkit-inline-box;
    }

    .cyc-margin {
        margin: 0 5px 0 10px;
    }

    .cyc-green {
        background-color: #7ED321;
        border: solid 1px #7ED321 !important;
    }

    .cyc-orange {
        background-color: #F5A623;
        border: solid 1px #F5A623 !important;
    }

    .cyc-red {
        background-color: #D0021B;
        border: solid 1px #D0021B !important;
    }

    .records-body {

    }

    .inspect-items {
        float: left;
        width: 40%;
        height: calc(100vh - 230px);
        overflow-y:scroll
    }

    .inspect-items .body-item {
        margin-right: 20px;

    }

    .report-items {
        float: right;
        width: 60%;
        height: calc(100vh - 230px);
        overflow-y:scroll
    }

    .report-items .body-item {
        margin-left: 20px;

    }
  .full{
     float:inherit;
             width: 100%;
               height:100%;
        overflow-y:hidden
        }
    .dispnone{
        display:none
    }
    .inspect-comment,
    .report-comment {
        padding:0 20px 10px;
        border: solid 1px #eceaea;
    }

    .body-top-title {
        color: #000;
        font-size: 1.2em;
    }

    .body-title {
        color: #000;
        margin: 20px 0 10px 0;
        font-weight: bold;
    }

    .val-title {
        color: #000;
        margin: 5px 0;
        font-weight: bold;
    }

    .val-val {
        min-height: 50px;
    }

    .suggestion-item {
        position: relative;
        margin: 10px 0;
        line-height: 20px;
    }

    .suggestion-title {
        color: #333;
        position: absolute;
        width: 100px;
    }

    .suggestion-content {
        padding-left: 100px;
        color:#666;
    }

    .inspect-item {
        margin-bottom: 20px;
        border: solid 1px #eceaea;
    }

    .inspect-head {
        background-color: #eee;
    }

    .head-title {
        position: relative;
        color: #000;
        display: inline-block;
        margin: 10px 0;
        width: 100%;
    }

    .info-title {
        color: #000;
        margin: 0 20px;
        font-weight: bolder;
    }

    .info-content {
        margin: 10px 20px 0 20px;
        color:#666;

    }
    .info-content.info-check-item-desc {
        line-height:1.45em;
        color:#666;
        margin-top:0;
    }

    .info-img {
        margin: 15px 20px 0 20px;
        line-height: 0;
    }

    .info-img img {
        cursor: pointer;
        height: 75px;
        width: 75px;
        margin-right: 15px;
        display: inline-block;
    }

    .inspect-add {
        display: block;
        margin-top: 20px;
        font-weight: bold;
        line-height: 40px;
        border: solid 1px #eceaea;
        text-align: center;
        color: #000;
    }

   

    .line {
        /* border-bottom: solid 1px #; */
        margin: 0 20px;
    }

    .record-user {
        text-align: right;
        margin: 10px 20px;
        font-weight: bold;
    }

    .record-head {
        margin: 10px 20px;
        position: relative;
    }

    .record-title {
        color: #000;
        margin-right: 120px;
        line-height:28px;
        font-weight:bold;
    }

    .m-left-20 {
        margin-left: 20px;
    }

    .record-action {
        position: absolute;
        right: 3px;
        top: -8px;
        width: 100px;
    }

    .record-action a {
        display: block;
        float: left;
        width: 30px;
    }

    .record-info {
        margin: 20px 0;
    }

    .info-lab {
        margin: 0 20px 0 20px;
    }
    .record-info .info-lab span{
        color:#666;
    }
    .record-info .info-lab span.el-tag--success{
        color:#67c23a;
    }
    .record-level {
        margin: 20px 20px 20px 10px;
        line-height:10px;

    }

    .record-level .cyc {
        border: solid 1px #eceaea;
        cursor: pointer;
    }

    .show {
        display: block;
    }

    .hide {
        display: none;
    }

    .report-item {

        margin-top: 20px;
        border: solid 1px #eceaea;
    }

    .big-img {
        max-width: 100%;
    }

    .add-img-list {
    }

    .add-img-btn {
        text-align: center;
    }

    .add-img-list img {
        width: 100px;
        height: 100px;
        margin: 5px;
        border: solid 3px #eceaea;
        cursor: pointer;
    }

    .add-img-list img.selected {
        border: solid 3px #409EFF;
    }
    .mt-20{
        margin-top: 20px;
    }
    .icon-zhuanjia{
        vertical-align: text-bottom;
        width: 20px;
    }
</style>
<style>
    .border-none textarea {
        border: none;
    }

    .textarea-bg textarea.el-textarea__inner {
        padding:0 0 12px 0;
        min-height: 24px;
    }
    .report-comment textarea.el-textarea__inner {
        padding: 12px 0;
        min-height: 24px;
        color:#666;
    }
    .report-comment .el-textarea .el-input__count {
        float:right;
    }
    .report-comment .el-form-item {
        margin-bottom:0;
    }
    .bgColor{
        background: #fdfdfd;
    }
</style>
